import { MockMethod } from "vite-plugin-mock";
import { DataSourceStatus, DataSourceType } from "@/types/dataSource";

// 模拟数据源列表
const dataSourceList = [
  {
    id: 1,
    name: "MySQL测试库",
    type: DataSourceType.MySQL,
    host: "localhost",
    port: 3306,
    database: "test_db",
    username: "root",
    password: "123456",
    status: DataSourceStatus.Connected,
    createdAt: "2023-06-01 10:00:00",
    updatedAt: "2023-06-01 10:00:00",
  },
  {
    id: 2,
    name: "PostgreSQL数据仓库",
    type: DataSourceType.PostgreSQL,
    host: "192.168.1.100",
    port: 5432,
    database: "data_warehouse",
    username: "postgres",
    password: "postgres",
    status: DataSourceStatus.Disconnected,
    createdAt: "2023-06-02 14:30:00",
    updatedAt: "2023-06-02 14:30:00",
  },
  {
    id: 3,
    name: "Oracle企业库",
    type: DataSourceType.Oracle,
    host: "oracle-server",
    port: 1521,
    database: "ORCL",
    username: "system",
    password: "manager",
    status: DataSourceStatus.Error,
    createdAt: "2023-06-03 09:15:00",
    updatedAt: "2023-06-03 09:15:00",
  },
];

// 延迟函数
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export default [
  // 获取数据源列表
  {
    url: "/admin-api/datasource/list",
    method: "get",
    response: async (req: any) => {
      console.log("Mock 接收到请求:", req.url, req.query); // 添加日志
      await delay(500);
      const { keyword, page = 1, pageSize = 10 } = req.query;

      let filtered = [...dataSourceList];

      // 如果有关键字，进行过滤
      if (keyword) {
        filtered = filtered.filter((item) =>
          item.name.toLowerCase().includes(keyword.toLowerCase())
        );
      }

      // 分页
      const start = (page - 1) * pageSize;
      const end = start + pageSize;
      const paged = filtered.slice(start, end);

      const response = {
        code: 0,
        message: "成功",
        data: {
          list: paged,
          total: filtered.length,
        },
      };

      console.log("Mock 响应数据:", response); // 添加日志
      return response;
    },
  },

  // 创建数据源
  {
    url: "/admin-api/datasource/create",
    method: "post",
    response: async (req: any) => {
      await delay(500);
      const newDataSource = {
        ...req.body,
        id: dataSourceList.length + 1,
        status: DataSourceStatus.Disconnected,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      dataSourceList.push(newDataSource);

      return {
        code: 0,
        message: "创建成功",
        data: newDataSource,
      };
    },
  },

  // 更新数据源
  {
    url: "/admin-api/datasource/update",
    method: "put",
    response: async (req: any) => {
      await delay(500);
      const { id } = req.query;
      const index = dataSourceList.findIndex((item) => item.id === Number(id));

      if (index === -1) {
        return {
          code: 404,
          message: "数据源不存在",
          data: null,
        };
      }

      dataSourceList[index] = {
        ...dataSourceList[index],
        ...req.body,
        updatedAt: new Date().toISOString(),
      };

      return {
        code: 0,
        message: "更新成功",
        data: dataSourceList[index],
      };
    },
  },

  // 删除数据源
  {
    url: "/admin-api/datasource/delete",
    method: "delete",
    response: async (req: any) => {
      await delay(500);
      const { id } = req.query;
      const index = dataSourceList.findIndex((item) => item.id === Number(id));

      if (index === -1) {
        return {
          code: 404,
          message: "数据源不存在",
          data: null,
        };
      }

      dataSourceList.splice(index, 1);

      return {
        code: 0,
        message: "删除成功",
        data: null,
      };
    },
  },

  // 测试数据源连接
  {
    url: "/admin-api/datasource/test",
    method: "post",
    response: async (req: any) => {
      await delay(1000);
      const { id } = req.query;
      const dataSource = dataSourceList.find((item) => item.id === Number(id));

      if (!dataSource) {
        return {
          code: 404,
          message: "数据源不存在",
          data: {
            success: false,
            message: "数据源不存在",
          },
        };
      }

      // 模拟连接成功率80%
      const success = Math.random() > 0.2;

      return {
        code: 0,
        message: "测试完成",
        data: {
          success,
          message: success ? "连接成功" : "连接失败，请检查配置",
        },
      };
    },
  },

  // 获取表列表
  {
    url: "/admin-api/datasource/:id/tableList",
    method: "get",
    response: async (req: any) => {
      await delay(500);
      return {
        code: 0,
        message: "成功",
        data: {
          tables: [
            { name: "users", comment: "用户表", type: "table" },
            { name: "orders", comment: "订单表", type: "table" },
            { name: "products", comment: "商品表", type: "table" },
          ],
          views: [
            { name: "order_details", comment: "订单详情视图", type: "view" },
            { name: "product_stats", comment: "商品统计视图", type: "view" },
          ],
        },
      };
    },
  },

  // 获取表结构
  {
    url: "/admin-api/datasource/:id/tableStructure",
    method: "get",
    response: async (req: any) => {
      await delay(500);
      return {
        code: 0,
        message: "成功",
        data: [
          {
            name: "id",
            type: "int",
            nullable: false,
            key: "PRI",
            comment: "主键ID",
          },
          {
            name: "name",
            type: "varchar(50)",
            nullable: false,
            comment: "名称",
          },
          {
            name: "status",
            type: "tinyint",
            nullable: false,
            default: "1",
            comment: "状态",
          },
          {
            name: "created_at",
            type: "datetime",
            nullable: true,
            comment: "创建时间",
          },
        ],
      };
    },
  },

  // 获取表数据
  {
    url: "/admin-api/datasource/:id/tableData",
    method: "post",
    response: async (req: any) => {
      await delay(500);
      const { page = 1, pageSize = 10 } = req.body;

      const mockData = Array.from({ length: 100 }, (_, i) => ({
        id: i + 1,
        name: `测试数据 ${i + 1}`,
        status: Math.random() > 0.5 ? 1 : 0,
        created_at: new Date().toISOString(),
      }));

      const start = (page - 1) * pageSize;
      const end = start + pageSize;

      return {
        code: 0,
        message: "成功",
        data: {
          list: mockData.slice(start, end),
          total: mockData.length,
        },
      };
    },
  },
] as MockMethod[];
